// miniprogram/pages/detail/detail.js
const DB = wx.cloud.database();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgList:'',
    fileIDs:"",
    gameModel:'',
    openid:''
  
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    wx.cloud.database().collection("active_list")
    .where({
        _id: options.id
    })
    .get()
    .then(res => {
      console.log(res)
        if (res.data.length > 0) {
           this.setData({
                gameModel: res.data[0],                        
            })}})

 this.setData({
  openid:options.openid
 })
  },
  // 选择图片
  ChooseImage() {
      wx.chooseImage({
        count: 1, //默认9,我们这里最多选择8张
        sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: (res) => {
          console.log("选择图片成功", res)
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(res.tempFilePaths)
            })
          } else {
            this.setData({
              imgList: res.tempFilePaths
            })
          }
        }
      })
  },
    //删除图片
    DeleteImg(e) {
      console.log("e", e.currentTarget.dataset.index)
      this.data.imgList.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        imgList: this.data.imgList
      })
    },
    // 皮肤名字
    getInput_name(event){
      this.setData({
       xieziname: event.detail
      })
    }
    ,
    // 积分数量
    getInput_jiage(event){
      this.setData({
       jiage: event.detail
       })
    },
    //上传数据
  publish() {
    const Promise_arr = [];
    Promise.all(Promise_arr).then(res => {
      wx.showLoading({
        title: '发布中....',
      })
      const promiseArr = []
      //只能一张张上传 遍历临时的图片数组
      for (let i = 0; i < this.data.imgList.length; i++) {
        let filePath = this.data.imgList[i]
        let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式，获取文件扩展名
        //在每次上传的时候，就往promiseArr里存一个promise，只有当所有的都返回结果时，才可以继续往下执行
        promiseArr.push(new Promise((reslove, reject) => {
          wx.cloud.uploadFile({
            cloudPath: 'myimages/' + new Date().getTime() + suffix,
            filePath: filePath, // 文件路径
          }).then(res => {
            // get resource ID
            console.log("上传结果", res.fileID)
            this.setData({
              fileIDs: this.data.fileIDs.concat(res.fileID)
            })
            reslove()
          }).catch(error => {
            console.log("上传失败", error)
          })
        }))
      }
      //保证所有图片都上传成功
      Promise.all(promiseArr).then(res => {
     let that=this
        wx.cloud.database().collection('game').add({
          data: {
              avatarUrl: that.data.fileIDs,
              nickName: that.data.xieziname,
              items: that.data.gameModel.items,
              creater_info: that.data.gameModel.creater_info,
              name: that.data.gameModel.name,
              draw_count: that.data.gameModel.draw_count,
              _id: that.data.gameModel._id + that.data.openid, //参与活动id
              gameXY: that.data.gameModel._id ,//抽奖活动id
              control:'是'
          },
          success(res) {
              wx.showToast({
                  title: '参与成功',
                  icon: 'success',
                  duration: 1000
              })
              console.log('新增game', res)
              that.drawc()

              if (that.data.gameModel.draw_count == that.data.gameModel.total_count+1) {
                  wx.showLoading({
                      title: '开奖中',
                  })
                  that.drawd()
              }
          },
          fail(res) {
              console.log('新增hf', res)
          }

      })
        
      })
    }).catch(res => {
      console.log("非法信息", err)
      wx.showToast({
        icon: "none",
        duration: 2000,
        title: '请删除敏感信息'
      })
      return
    })
    
  },
      //存获奖信息 //修改参与人数
      drawc: function () {
        let that=this
        wx.cloud.callFunction({
            name: 'update',
            data: {
                action:'join-count',
                _id: this.data.gameModel._id
            }
        }).then(res => {
          wx.cloud.database().collection("active_list")
            .where({
                _id: that.data.gameModel.gameXY
            })
            .get()
            .then(res => {
                if(res.data.length>0)
{this.setData({
    gameModel:res.data[0]
})}
            })
            console.log("drawc", res)
        }).catch(err => {
            console.log(err)
        })
    },
})